package cover

import (
	"CodeCover/internal/log"
	"bufio"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"html/template"
	"io"
	"math"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"

	"golang.org/x/tools/cover"
)

type CoverInfo struct {
	TotalTrackedLine int
	TotalCoverLine   int
}

type templateFile struct {
	Name     string
	Body     template.HTML
	Coverage float64
	NumStmt  int
	Count    int
}

type templateData struct {
	Files []*templateFile
	Set   bool
}

func GoHtmlOutput(profilePath string) error {

	// 解析 coverage.out, 每个文件生成一个 profile
	profiles, err := cover.ParseProfiles(profilePath)
	if err != nil {
		return err
	}

	// print
	// fmt.Print("profiles:\n")
	log.Logger.Info("Profiles:\n")
	for k, v := range profiles {
		log.Logger.Info(k, v)
	}
	var d templateData

	// 切换 profilePath 目录下运行 go list -e -json
	// dirs: key = packageName, value = *Pkg{ImportPath, AbsDir, Err}
	dirs, err := findPkgs(profilePath, profiles)
	if err != nil {
		return err
	}

	log.Logger.Info("dirs\n")
	for key, value := range dirs {
		log.Logger.Infof("dirs :Key: %v, Value: %v\n", key, value)
	}

	var totalStat, totalCoveredStat int
	for _, profile := range profiles {
		fn := profile.FileName
		if profile.Mode == "set" {
			d.Set = true
		}

		log.Logger.Info("dirs=", dirs, "fn=", fn)

		// 遍历coverage.out下的每个文件, 根据其包名得到绝对路径file
		file, err := findFile(dirs, fn)
		if err != nil {
			return err
		}

		log.Logger.Info("Read abs filepath:", file)
		src, err := os.ReadFile(file)
		if err != nil {
			return err
		}
		var buf strings.Builder

		err = htmlGen(&buf, src, profile.Boundaries(src))
		if err != nil {
			return err
		}

		d.Files = append(d.Files, &templateFile{
			Name:     fn,
			Body:     template.HTML(buf.String()),
			Coverage: percentCovered(profile),
			NumStmt:  numTrackedStmt(profile),
			Count:    numCoveredStmt(profile),
		})

		totalStat += numTrackedStmt(profile)
		totalCoveredStat += numCoveredStmt(profile)

	}

	for _, value := range d.Files {
		htmlDir := filepath.Join(filepath.Dir(filepath.Dir(profilePath)), "/html/"+value.Name)
		parentPath := filepath.Dir(htmlDir)
		if err := os.MkdirAll(parentPath, 0755); err != nil {
			log.Logger.Errorf("错误：创建目录失败 %s: %v\n", parentPath, err)
			return err
		}

		out, err := os.Create(htmlDir)

		if err != nil {
			log.Logger.Error(err)
			return err
		}

		err = htmlTemplate.Execute(out, value)

		if err != nil {
			log.Logger.Error(err)
			return err
		}
		if err2 := out.Close(); err2 != nil {
			log.Logger.Error(err)

			return err2
		}
	}

	return nil
}

type Pkg struct {
	ImportPath string
	Dir        string
	Error      *struct {
		Err string
	}
}

func findPkgs(profilepath string, profiles []*cover.Profile) (map[string]*Pkg, error) {
	// Run go list to find the location of every package we care about.
	pkgs := make(map[string]*Pkg)
	var list []string
	for _, profile := range profiles {
		if strings.HasPrefix(profile.FileName, ".") || filepath.IsAbs(profile.FileName) {
			// Relative or absolute path.
			continue
		}
		pkg := path.Dir(profile.FileName)
		if _, ok := pkgs[pkg]; !ok {
			pkgs[pkg] = nil
			list = append(list, pkg)
		}
	}

	if len(list) == 0 {
		return pkgs, nil
	}
	// Note: usually run as "go tool cover" in which case $GOROOT is set,
	// in which case runtime.GOROOT() does exactly what we want.
	// goTool := filepath.Join(runtime.GOROOT(), "bin/go")
	cmd := exec.Command("go", append([]string{"list", "-e", "-json"}, list...)...)
	cmd.Dir = filepath.Dir(profilepath)
	var stderr bytes.Buffer
	cmd.Stderr = &stderr
	stdout, err := cmd.Output()

	if err != nil {
		return nil, fmt.Errorf("cannot run go list: %v\n%s", err, stderr.Bytes())
	}
	dec := json.NewDecoder(bytes.NewReader(stdout))
	for {
		var pkg Pkg
		err := dec.Decode(&pkg)
		if err == io.EOF {
			break
		}

		parts := strings.Split(pkg.ImportPath, "/")
		if pkg.Error != nil && pkg.Error.Err != "" {
			pkg.Dir = filepath.Join(filepath.Dir(profilepath), strings.Join(parts[1:], "/"))
		}
		if err != nil {
			return nil, fmt.Errorf("decoding go list json: %v", err)
		}
		pkgs[pkg.ImportPath] = &pkg
	}
	return pkgs, nil
}

func findFile(pkgs map[string]*Pkg, file string) (string, error) {
	if strings.HasPrefix(file, ".") || filepath.IsAbs(file) {
		// Relative or absolute path.
		return file, nil
	}
	// for k, v := range pkgs {
	// 	fmt.Println("pkgs", k, v.Dir, v.Error, v.ImportPath)
	// }
	pkg := pkgs[path.Dir(file)]
	if pkg != nil {
		if pkg.Dir != "" {
			return filepath.Join(pkg.Dir, path.Base(file)), nil
		}
		if pkg.Error != nil {
			return "", errors.New(pkg.Error.Err + "myeror")
		}
	}
	return "", fmt.Errorf("did not find package for %s in go list output", file)
}
func rgb(n int) string {
	if n == 0 {
		return "rgb(192, 0, 0)" // Red
	}
	// Gradient from gray to green.
	r := 128 - 12*(n-1)
	g := 128 + 12*(n-1)
	b := 128 + 3*(n-1)
	return fmt.Sprintf("rgb(%v, %v, %v)", r, g, b)
}

func colors() template.CSS {
	var buf strings.Builder
	for i := 0; i < 11; i++ {
		fmt.Fprintf(&buf, ".cov%v { color: %v }\n", i, rgb(i))
	}
	return template.CSS(buf.String())
}

var htmlTemplate = template.Must(template.New("html").Funcs(template.FuncMap{
	"colors":  colors,
	"percent": percent,
}).Parse(tmplHTML))

// PackageName returns a name for the package being shown.
// It does this by choosing the penultimate element of the path
// name, so foo.bar/baz/foo.go chooses 'baz'. This is cheap
// and easy, avoids parsing the Go file, and gets a better answer
// for package main. It returns the empty string if there is
// a problem.
func (td templateData) PackageName() string {
	if len(td.Files) == 0 {
		return ""
	}
	fileName := td.Files[0].Name
	elems := strings.Split(fileName, "/") // Package path is always slash-separated.
	// Return the penultimate non-empty element.
	for i := len(elems) - 2; i >= 0; i-- {
		if elems[i] != "" {
			return elems[i]
		}
	}
	return ""
}

const tmplHTML = `
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Go Coverage Report</title>
        <style>
            body {
                background: black;
                color: rgb(80, 80, 80);
            }
            body, pre, #legend span {
                font-family: Menlo, monospace;
                font-weight: bold;
            }
            #topbar {
                background: black;
                position: fixed;
                top: 0; left: 0; right: 0;
                height: 42px;
                border-bottom: 1px solid rgb(80, 80, 80);
            }
            #content {
                margin-top: 50px;
            }
            #nav, #legend {
                float: left;
                margin-left: 10px;
            }
            #legend {
                margin-top: 12px;
            }
            #nav {
                margin-top: 10px;
            }
            #legend span {
                margin: 0 5px;
            }
            /* 新增样式类，设置其他文字的颜色 */
            .other-text {
                color: #ffffff; /* 可根据需求修改颜色值 */
            }
            {{colors}}
        </style>
    </head>
    <body>
        <div id="topbar">
            <div id="legend">
                <span class="other-text">not tracked</span>
                <span class="cov0">not covered</span>
                <span class="cov8">covered</span>
                <span class="other-text">Total:{{.NumStmt}}</span>
                <span class="other-text">Covered:{{.Count}}</span>
                <span class="other-text">CoveredPercent:{{percent .Count .NumStmt}}</span>
            </div>
        </div>
        <div id="content">
            <pre class="file other-text" id="file" >{{.Body}}</pre>
        </div>
    </body>
</html>
`

func percent(count, total int) string {
	if total == 0 {
		return "0.0%"
	}
	p := float64(count) / float64(total) * 100
	return fmt.Sprintf("%.1f%%", p)
}
func htmlGen(w io.Writer, src []byte, boundaries []cover.Boundary) error {

	dst := bufio.NewWriter(w)
	for i := range src {
		for len(boundaries) > 0 && boundaries[0].Offset == i {
			b := boundaries[0]
			if b.Start {
				n := 0
				if b.Count > 0 {
					n = int(math.Floor(b.Norm*9)) + 1
				}
				fmt.Fprintf(dst, `<span class="cov%v" title="%v">`, n, b.Count)
			} else {
				dst.WriteString("</span>")
			}
			boundaries = boundaries[1:]
		}
		switch b := src[i]; b {
		case '>':
			dst.WriteString("&gt;")
		case '<':
			dst.WriteString("&lt;")
		case '&':
			dst.WriteString("&amp;")
		case '\t':
			dst.WriteString("        ")
		default:
			dst.WriteByte(b)
		}
	}
	return dst.Flush()
}

func percentCovered(p *cover.Profile) float64 {
	var total, covered int64
	for _, b := range p.Blocks {
		total += int64(b.NumStmt)
		if b.Count > 0 {
			covered += int64(b.NumStmt)
		}
	}
	if total == 0 {
		return 0
	}
	return float64(covered) / float64(total) * 100
}

func numTrackedStmt(p *cover.Profile) int {
	var tracked int
	for _, b := range p.Blocks {
		tracked += b.NumStmt
	}
	return tracked
}

func numCoveredStmt(p *cover.Profile) int {
	var covered int
	for _, b := range p.Blocks {
		if b.Count > 0 {
			covered += b.NumStmt
		}
	}
	return covered
}
